<script setup>
import {ref, inject} from 'vue'
import {ElForm,ElMessage,ElMessageBox} from 'element-plus'
import axios from 'axios'

const userinfo=inject("userinfo")
const mitt=inject('mitt')
const model=defineModel()

/////////////////////////////////
// 登录
/////////////////////////////////
const ref_form_login=ref()
const form_login=ref({
    mobile_email:'admin@china.com',
    password:'test'
})

function validateMobileEmail(rule,value,callback){
    if(/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/.test(value.trim())||
    /^0?(13|14|15|18|19|17)[0-9]{9}$/.test(value.trim())){
        callback()
    }else{
        callback(new Error('手机号或邮箱格式有误'))
    }
}

const rules_login=ref({
    mobile_email:[{required:true,trigger:'blur',validator:validateMobileEmail}],
    password:[{required:true,message:"密码不能为空"}]
})

// * 409 手机号或邮箱格式有误
// * 404 未找到用户
// * 401 密码错误
// * 500 内部错误
// * 200 返回用户信息
function handleSubmitFormLogin(form){
    form.validate((valid)=>{
        if(valid){
            axios.get(
                `/api/user/login?mobile_email=${form_login.value.mobile_email}&password=${form_login.value.password}`
            ).then((res)=>{
                sessionStorage.setItem('userinfo',JSON.stringify(res.data))
                userinfo.value=res.data
                mitt.emit('login')
                model.value=false
            }).catch((e)=>{
                switch(e.response.status){
                    case 409:
                        ElMessageBox.alert("手机号或邮箱格式有误",{type:'warning'})
                        break;
                    case 404:
                        ElMessageBox.alert("未找到用户",{type:'warning'})
                        break;
                    case 401:
                        ElMessageBox.alert("密码错误",{type:'warning'})
                        break;
                    case 500:
                        ElMessageBox.alert("内部错误，请联系管理员",{type:'warning'})
                        break;
                    default:
                        console.log(e)
                }
            })
        }else{
            return false
        }
    })
}
function handleResetForm(form){
    form.resetFields()
}
function handleCloseForm(){
    model.value=false
}

/////////////////////////////////
// 注册
/////////////////////////////////
const ref_form_register=ref()
const form_register=ref({
    name:'',
    id_code:'',
    mobile:'',
    email:'',
    password1:'',
    password2:''
})
const rules_register=ref({
    name:[{required:true,message:'请输入姓名'}],
    id_code:[{required:true,trigger:'blur',validator:validateIdCode}],
    mobile:[{required:true,trigger:'blur',validator:validateMobile}],
    email:[{required:true,trigger:'blur',validator:validateEmail}],
    password1:[{required:true,trigger:'blur',message:"请输入密码"}],
    password2:[{required:true,trigger:'blur',validator:validatePassword}]
})
function validateIdCode(rule,value,callback){
    if(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value.trim())){
        callback()
    }else{
        callback(new Error('身份证格式有误'))
    }
}
function validateMobile(rule,value,callback){
    if(/^0?(13|14|15|18|19|17)[0-9]{9}$/.test(value.trim())){
        callback()
    }else{
        callback(new Error('手机号格式有误'))
    }
}
function validateEmail(rule,value,callback){
    if(/^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/.test(value.trim())){
        callback()
    }else{
        callback(new Error('邮箱格式有误'))
    }
}
function validatePassword(rule,value,callback){
    if(value==''){
        callback(new Error('请重复密码'))
    }else if(value!=form_register.value.password1){
        callback(new Error('两次输入的密码不同'))
    }else{
        callback()
    }
}
const active_tab=ref('login')
/**
* 406 数据格式有误
* 409 unique约束冲突
* 500 内部错误
* 200 返回用户信息
*/
function handleSubmitFormRegister(form){
    form.validate((valid)=>{
        if(!valid) return false
        axios.post(
            '/api/user/register',
            form_register.value
        ).then(res=>{
            ElMessage.success("注册成功")
            form_login.value.mobile_email=res.data.mobile
            form_login.value.password=res.data.password
            ref_form_register.value.resetFields()
            active_tab.value='login'
        }).catch(e=>{
            switch(e.response.status){
                case 406:
                    ElMessage.error("数据格式有误")
                    break;
                case 409:
                    ElMessage.error("身份证/手机号/邮箱与数据库已有数据冲突")
                    break;
                case 500:
                    ElMessage.error("内部错误")
                    break;
                default:
                    ElMessage.error("未知错误")
            }
        })
    })
}
</script>

<template>
<transition name="el-zoom-in-top">
    <div class="parent" v-if="model">
    <div class="child">
        <el-tabs type="border-card" v-model="active_tab">
            <el-tab-pane label="登录" name="login">
                <el-form ref="ref_form_login" label-position="top" :model="form_login" :rules="rules_login" status-icon>
                    <el-form-item label="手机号/邮箱" prop="mobile_email">
                        <el-input v-model.trim="form_login.mobile_email"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model.trim="form_login.password" type="password"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmitFormLogin(ref_form_login)">提交</el-button>
                        <el-button @click="handleResetForm(ref_form_login)">重置</el-button>
                        <el-button @click="handleCloseForm">关闭</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="注册" name="register">
                <el-form ref="ref_form_register" label-position="top" :model="form_register" :rules="rules_register" status-icon>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model.trim="form_register.name"/>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="id_code">
                        <el-input v-model.trim="form_register.id_code"/>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model.trim="form_register.mobile"/>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model.trim="form_register.email"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password1">
                        <el-input v-model.trim="form_register.password1" show-password/>
                    </el-form-item>
                    <el-form-item label="重复密码" prop="password2">
                        <el-input v-model.trim="form_register.password2" show-password/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSubmitFormRegister(ref_form_register)">提交</el-button>
                        <el-button @click="handleResetForm(ref_form_register)">重置</el-button>
                        <el-button @click="handleCloseForm">关闭</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
</div>
</transition>
</template>

<style scoped>
.parent{
    z-index:100;
    position:absolute;
    top:0;
    left:0;
    width:100vw;
    height:100vh;
    background-color: rgba(128,128,128,0.6);
    display:flex;
    align-items:center;
    justify-content:center;
}
.child{
    width:300px;
    height:auto;
    background-color: white;
    border-radius:10px;
    box-shadow: 4px 4px 6px rgba(0, 0, 0, 0.3);
}
</style>